import React, {Component} from 'react';

/**
 * 获取URL中参数值
 * @param  {string} name [需要获取的URL参数名称]
 * @return {string}      [获取的URL参数值]
 */
function getQueryString(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    const r = window.location.search.substr(1).match(reg);
    if (r !== null) return decodeURI(r[2]);
    return null;
}

import imgFail from "../../common/img/icon-error.png";
import imgSuccess from "../../common/img/icon-right.png";
const boxStyle = {
    width: "100vw",
    height: "100vh",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
};
const imgStyle = {float: "left", margin: "5px 10px", width: 40, height: 40};
const textStyle = {fontSize: 14, color: "#999"};
const AuthSuccess = function ({count}) {
    return (
        <div style={{width: 300}}>
            <img src={imgSuccess} style={imgStyle}/>
            <h2 style={{fontSize: 24, color: "#45be89"}}> 恭喜,授权成功</h2>
            <p style={textStyle}>页面将在{count}s后关闭</p>
        </div>
    )
};

const AuthFail = function ({close, content}) {
    return (
        <div style={{width: 300}}>
            <img src={imgFail} style={imgStyle}/>
            <h2 style={{fontSize: 24, color: "#f36a5a"}}> {content} </h2>
            <p style={{...textStyle, textAlign: "center"}}>
                请返回页面重新尝试&nbsp;
                <a style={{color: "#5491de", textDecoration: "none"}} href="javascript:;" onClick={close}>关闭窗口</a>
            </p>
        </div>
    )
};


class Authorization extends Component {
    constructor(props) {
        super(props);
        this.state = {
            status: -1,
            count: 5,
            content: "授权失败"
        }
    }

    componentDidMount() {
        this.bindAccount().then(res => res.json()).then(data => {
            console.log(data);
            if (data.errcode) {
                this.setState({
                    status: 0,
                    content: "授权失败:" + data.errmsg
                });
                return;
            }
            this.setState({status: 1});
            this.close();
        }).catch((err) => {
            this.setState({status: 0});
        })
    }

    render() {
        return (
            <div style={boxStyle}>
                {this.state.status === 1 && <AuthSuccess count={this.state.count }/>}
                {this.state.status === 0 &&
                <AuthFail content={this.state.content} count={this.state.count} close={() => window.close()}/>}
            </div>
        )
    }

    bindAccount = () => {
        return fetch('/api/authorizer/bind', {
            credentials: 'include',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({authCode: getQueryString('auth_code') || ""})
        })
    };

    close = () => {
        const timer = setInterval(() => {

            if (this.state.count === 0) {
                clearInterval(timer);
                console.log("关闭页面");
                window.close();
                return;
            }
            this.setState((prevState) => {
                return {count: prevState.count - 1};
            });
        }, 1000);
    }
}

export default Authorization;
